package com.app.oral.config

import com.app.oral.model.PaperType
import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.MappedTypes
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException

/**
 * 试卷类型自定义TypeHandler
 * 处理数据库字符串与PaperType枚举之间的映射
 */
@MappedTypes(PaperType::class)
class PaperTypeTypeHandler : BaseTypeHandler<PaperType>() {

    @Throws(SQLException::class)
    override fun setNonNullParameter(ps: PreparedStatement, i: Int, parameter: PaperType, jdbcType: JdbcType?) {
        ps.setString(i, parameter.value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnName: String): PaperType? {
        val value = rs.getString(columnName)
        return mapStringToPaperType(value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnIndex: Int): PaperType? {
        val value = rs.getString(columnIndex)
        return mapStringToPaperType(value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(cs: CallableStatement, columnIndex: Int): PaperType? {
        val value = cs.getString(columnIndex)
        return mapStringToPaperType(value)
    }

    /**
     * 将数据库字符串值映射到PaperType枚举
     */
    private fun mapStringToPaperType(value: String?): PaperType? {
        if (value == null) return null
        
        return when (value.lowercase()) {
            "practice" -> PaperType.PRACTICE
            "test" -> PaperType.TEST
            else -> {
                // 尝试按枚举名称匹配
                try {
                    PaperType.valueOf(value.uppercase())
                } catch (e: IllegalArgumentException) {
                    // 默认为练习试卷
                    PaperType.PRACTICE
                }
            }
        }
    }
}